package com.example.demo.controller;

import com.example.demo.commen.AppResult;
import com.example.demo.commen.ResultCode;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.User;
import com.example.demo.service.impl.UserServiceImpl;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserServiceImpl userService;


    @ApiOperation("用户注册")
    @RequestMapping(method = RequestMethod.POST,value = "register")
    public AppResult createUser(@ApiParam("用户名")  @RequestParam(value = "username") String username,
                                @ApiParam("昵称")   @RequestParam(value = "nickname") String nickname,
                                @ApiParam("密码")  @RequestParam(value = "password") String password,
                                @ApiParam("重复密码")   @RequestParam(value = "passwordRepeat") String passwordRepeat
                              ){

        if (!StringUtils.hasLength(username)
                || !StringUtils.hasLength (password)
                || !StringUtils.hasLength(passwordRepeat)
                ||!StringUtils.hasLength(nickname)) {
// 记录⽇志
            log .info(ResultCode. FAILED_PARAMS_VALIDATE .toString());

// 返回错误信息
            return AppResult. failed (ResultCode. FAILED_PARAMS_VALIDATE.toString());
        }
// 1.基本信息赋值
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
// 2.处理密码
// 2.1 校验密码和确认密码是否相等
        if (!password.equals(passwordRepeat)) {
// 记录⽇志
            log .info(ResultCode. FAILED_PARAMS_VALIDATE .getMessage());
// 返回错误信息
            return AppResult. failed (ResultCode. FAILED_PARAMS_VALIDATE.getMessage() );
        }
// 2.2 加密密码
        String salt = UUIDUtil.UUId_32();   //通过UUID随机生成一个字符串，然后和经过MD5加密的密码再次加密存如数据库，这个随机字符串（盐）也需要存入
        String encryptPassword =MD5Util.md5Last(password,salt);

// 2.3 设置密码
        user.setPassword(encryptPassword);
        user.setSalt(salt);
// 3. 调⽤Service   这个里面对用户名进行了检验存在不存在，但是还是开始的时候进行校验比较好
        userService.createUser(user);
        System.out.println("xaxadda");
// 4. 返回
        return AppResult. success();

    }

    @ApiOperation("用户登录")
    @RequestMapping(method = RequestMethod.POST,value = "login")
    public AppResult login(@ApiParam("用户名")@RequestParam(value = "username") String username,
                           @ApiParam("密码") @RequestParam("password") String password
            , HttpServletRequest request){

        if(!StringUtils.hasLength(username)||username==null||password==null||!StringUtils.hasLength(password)){
            throw  new ApplicationException("用户名或者密码没有输入");
        }
          boolean flag = userService.login(username,password);
        if(!flag){
            throw  new ApplicationException(ResultCode.FAILED.getMessage());
        }
         User user = userService.getUserByName(username);

        HttpSession session = request.getSession(true);
        session.setAttribute("userInfo",user);
        return AppResult.success();
                                                             //这里最好不要用session因为在集群的一个环境下就会发生错误
         /* Map<String,Object> map = new HashMap<>();
          map.put("id",user.getId());
          map.put("username",user.getUsername());           //假如登录在一个服务器完成，那这个服务器就会存储session，
         String token = TokenUtil.generateToken(map);      //当用户请求下一个页面的时候，由于负载均衡下个页面的请求就可能
        System.out.println(token);                         //在另一个服务器上，另一个服务器由于没有存储session，所以就会发生错误
                                                          //由于这个原因我们就采用token；
        return AppResult.success(token);*/
    }


    //这个请求的功能主要是如果前端发来了Id（所以的设置Id为非必传项），那么查询的就是发来Id的用户，如果
    //没有发来ID，那么就默认查询的是登录用户的信息
    @ApiOperation("根据用户ID查询")
    @RequestMapping(method = RequestMethod.GET,value = "/info")    //这里的@RequestParam有一个required=false，代表为非必传参数
    public AppResult<User> getUserInfo(@ApiParam("用户Id")@RequestParam(value = "id",required = false) Long id
            ,HttpServletRequest request){
        if(id==null){
                HttpSession session = request.getSession(false);

            System.out.println("11111");
            System.out.println(session);
                if(session==null||session.getAttribute("userInfo")==null){               //这个就是前端没有发来ID的情况，所以应该查询的是登录用户的信息
                                            //但是如果session也为空，说明都没登陆
             throw  new ApplicationException("用户未登录");   //这里我想repose.status(401)  return,然后前端就可以收到ERROR，然后跳转到登录页面
                }
             User user = (User) session.getAttribute("userInfo");
                return AppResult.success(user);
        }
         User user = userService.getUserById(id);

        return  AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @RequestMapping(method = RequestMethod.GET,value = "/layout")

    public AppResult layout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        System.out.println(session);

        User user = (User) session.getAttribute("userInfo");

        if(user==null){
            throw new ApplicationException("用户未登录");
        }
        session.removeAttribute("userInfo");
        return AppResult.success("退出登录成功");
    }

    @ApiOperation("修改个人信息")
    @RequestMapping(method =RequestMethod.POST,value = "/modifyInfo")

    public AppResult modifyUserInfo( HttpServletRequest request,
                                     @ApiParam("用户名")@RequestParam(value = "username",required = false)  String username,
                                     @ApiParam("昵称")@RequestParam(value = "nickname",required = false) String nickname,
                                     @ApiParam("电话")@RequestParam(value = "phoneNum",required = false) String phoneNum,
                                     @ApiParam("邮箱")@RequestParam(value = "email",required = false) String email,
                                     @ApiParam("性别")@RequestParam(value = "gender",required = false)  Byte gender,
                                     @ApiParam("个人简介")@RequestParam(value = "remark",required = false)String remark) {

        if(username==null&&nickname==null&& phoneNum==null&&email==null&& gender==null&&remark==null){    //全部为空才报错

            throw  new ApplicationException("参数异常");
        }
     HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("userInfo");
        if(user.getId()==null||user.getId()<=0){
            throw  new ApplicationException("用户不存在");
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);
        log.info("更新成功");

        User user1 = userService.getUserById(updateUser.getId());   //重新获取修改后用户的新信息，然后更新session
        session.setAttribute("userInfo",user1);
        return AppResult.success(user1);

    }

    @ApiOperation("修改密码")
    @RequestMapping(method = RequestMethod.POST,value = "/alterPassword")

    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码")@RequestParam("password")@NonNull String password,
                                    @ApiParam("新密码")@RequestParam("newPassword")@NonNull String newPassword,
                                    @ApiParam("确认密码")@RequestParam("confirmPassword")@NonNull String confirmPassword
                                    ){

                    HttpSession session = request.getSession(false);
                    User user = (User) session.getAttribute("userInfo");
                    if(user==null||user.getId()<=0){
                        throw new ApplicationException("用户不存在");
                    }


                    if(password==null||!StringUtils.hasLength(password)||newPassword==null||!StringUtils.hasLength(newPassword)||
                    confirmPassword==null||!StringUtils.hasLength(confirmPassword)||!newPassword.equals(confirmPassword)){
                        throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
                    }
                    User existUser = userService.getUserById(user.getId());
                    if(existUser==null||existUser.getId()<=0){
                        throw new ApplicationException("用户不存在");
                    }
                   if(!existUser.getPassword().equals(MD5Util.md5Last(password,existUser.getSalt()))){
                       throw new ApplicationException("原密码错误");
                   }
                    userService.updatePassword(password,newPassword, user.getId());

                   session.removeAttribute("userInfo");   //修改密码后，强制跳转到登录界面，让我们用户重新登录
                    return AppResult.success("修改密码成功");
    }


}
